﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DataControl;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using DAL.Dao;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Push;

namespace Auto
{
    public class CommonHelp
    {
        Random rd = new Random();
        DataAccess da = new DataAccess();
        MessageDao Md = new MessageDao();
        JPush _push = new JPush();
        

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public string GetInviteCode()
        {
            string strInvite = "";

            //生成随机10位码
            strInvite = GenerateRandom(10);

            //校验邀请码是否重复
            if (!CheckCode(strInvite))
            {
                GetInviteCode();
            }

            return strInvite;

        }

        #region 产生10位随机码
        //随机数 
        private static char[] constant = 
        { 
        '0','1','2','3','4','5','6','7','8','9', 
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' 
        };

        private static string GenerateRandom(int Length)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(62)]);
            }
            return newRandom.ToString();
        }
        #endregion

        /// <summary>
        /// 校验邀请码是否重复
        /// </summary>
        /// <param name="strInvite"></param>
        /// <returns></returns>
        private bool CheckCode(string strInvite)
        {
            DataAccess da = new DataAccess();
            string strSql = "";
            strSql = @"select count(1) count from T_SupplyCode where Code='{0}'";
            strSql = string.Format(strSql, strInvite);
            DataTable dtSCode = da.ExecuteDataTable(strSql);


            strSql = "";
            strSql = @"select count(1) count from T_AppUser where tauAdditional1='{0}'";
            strSql = string.Format(strSql, strInvite);
            DataTable dtAUser = da.ExecuteDataTable(strSql);

            if (dtSCode.Rows[0]["count"].ToString() == "0" && dtAUser.Rows[0]["count"].ToString() == "0")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 获取提示信息
        /// </summary>
        /// <param name="strType">提示信息Id即类型</param>
        /// <param name="strLagId">语言Id</param>
        /// <returns></returns>
        public string GetTips(string strType, string strLagId)
        {
            DataAccess da = new DataAccess();
            string strTips = "";

            string strSql = "select * from D_tips_multiLan where Tips_ID='{0}' and LanId='{1}'";
            strSql = string.Format(strSql, strType, strLagId);
            DataTable dt = da.ExecuteDataTable(strSql);

            if (dt == null && dt.Rows.Count == 0)
            {
                
                return strTips;
            }
            else
            {
                strTips = dt.Rows[0]["Desc"].ToString();
                return strTips;
            }
        }

       
       

        /// <summary>
        /// 创建报价数据并推送消息
        /// </summary>
        /// <returns></returns>
        public bool CreateResAndSendMess(string strRequestID)
        {
            

            Dictionary<string, object> parm = new Dictionary<string, object>();
            parm.Add("@RequestID",strRequestID);

            DataTable dt = da.GetDataTableBySPName("SP_ChoiceSupply", parm);

            if (dt == null || dt.Rows.Count == 0)
            {
                //没有合适的供应商,推送系统管理员
                #region 申明实体，并赋值
                T_Message Entry = new T_Message();
                Entry.tmType = "1";
                Entry.tmfrom = "system";
                Entry.tmto = "";
                Entry.tmTitle = "无适配分供商";
                Entry.tmMessage = Md.CreateMessageByRequestId(strRequestID, Entry.tmType);

                this.SendMessage(Entry,"2",new Dictionary<string,string>());
                #endregion

                return false;
            }
            //调用推送接口
            else
            {
                string strSql0 = @"update T_Request  set Is_Push='1'
                    where RequestID='{0}'";
                strSql0 = string.Format(strSql0,  strRequestID);
                da.ExcuteNoQuery(strSql0);

                foreach (DataRow dr in dt.Rows)
                {
                    #region 申明实体，并赋值
                    T_Message Entry = new T_Message();
                    Entry.tmType = "3";
                    Entry.tmfrom = "system";
                    Entry.tmto = dr["tauloginid"].ToString();
                    Entry.tmTitle = "询价单推送，请报价";
                    Entry.tmMessage = Md.CreateMessageByRequestId(strRequestID,Entry.tmType);

                    string strSql = @"select t.ResponseID
                    from T_Response t
                    where t.tauloginid='{0}' and t.RequestID='{1}'";

                    strSql = string.Format(strSql, dr["tauloginid"].ToString(), strRequestID);
                    
                    DataTable dt1 = da.ExecuteDataTable(strSql);

                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        
                        Dictionary<string, string> Parm = new Dictionary<string, string>();
                        Parm.Add("ResponseId", dt1.Rows[0]["ResponseID"].ToString());
                        this.SendMessage(Entry, "3", Parm);
                    }


                    
                    #endregion
                }
            }
            return true;
        }


        #region 格式转换
        /// <summary>
        /// DataTable转Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ConvertDataTableToJSON(DataTable dt)
        {
            JArray jRtn = new JArray();
            if (dt == null || dt.Rows.Count == 0)
                return JsonConvert.SerializeObject(jRtn);

            foreach (DataRow row in dt.Rows)
            {
                JObject jRow = new JObject();
                for (int i = 0; i < dt.Columns.Count; i++)
                    jRow[dt.Columns[i].ColumnName] = ConvertToString(row[i]);

                jRtn.Add(jRow);
            }

            return JsonConvert.SerializeObject(jRtn);
        }

        public string ConvertToString(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return "";

            return obj.ToString();
        }
        public bool ConvertToBool(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return false;

            if (obj is bool)
                return (bool)obj;

            return false;
        }
        public int ConvertToInt(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;

            int iRtn = 0;
            int.TryParse(obj.ToString(), out iRtn);
            return iRtn;
        }
        #endregion
        

        #region 推送信息
        //推送消息
        public bool SendMessage(T_Message TMessage,string strType,Dictionary<string,string> ParmKey)
        {
            DataAccess da = new DataAccess();
            bool blIsSend;
            bool blResult;
            int intResult = 0;
            JObject jo= new JObject();

            string strSql = @"INSERT INTO T_Message
                            (tmType,tmfrom,tmto,tmTitle,tmMessage,RowStatus,CreatedBy,CreatedDate,toType,toId)
                            VALUES
                            ('{0}','{1}','{2}',N'{3}',N'{4}',0,'system',GETDATE(),'{5}','{6}')";
            strSql = string.Format(strSql, TMessage.tmType, TMessage.tmfrom, TMessage.tmto, TMessage.tmTitle, TMessage.tmMessage, TMessage.toType, TMessage.toId);
            intResult = da.ExcuteNoQuery(strSql);


            
            #region 调用推送接口(待完善)

            //1.极光推送 2.邮箱推送 3.两者都推送
            switch (strType)
            {
                case "2":
                    intResult = this.SendEmailAsnyc(TMessage);
                    break;
                case "3":
                    
                    //邮件推送
                    intResult = this.SendEmailAsnyc(TMessage);
                    if (ParmKey.ContainsKey("ContractId") || ParmKey.ContainsKey("RequestId") || ParmKey.ContainsKey("ResponseId"))
                    {
                        //极光推送
                        _push.PushByAlias(TMessage.tmto, TMessage.tmMessage, ParmKey);
                    }
                    else
                    {
                        //极光推送
                        _push.PushByAlias(TMessage.tmto, TMessage.tmMessage);
                    }
                    break;
            }

            if (intResult != -1)
            {
                //da.ExecuteDataTable(
                //string.Format("update T_Message set RowStatus=1 where tmType='{0}' and tmfrom='{1}' and tmto='{2}' and tmMessage='{3}' and CreatedDate='{4}'",
                //TMessage.tmType, TMessage.tmfrom, TMessage.tmto, TMessage.tmMessage, TMessage.CreatedDate));
                blIsSend = true;
            }
            else
            {
                blIsSend = false;
            }
            #endregion

            if (intResult == 1 && blIsSend == true)
            {
                blResult = true;
            }
            else
            {
                blResult = false;
            }



            if (blResult)
            {
                return true;
            }
            else
            {
                return false;
            }

        }


        /// <summary>
        /// 邮箱发送消息
        /// </summary>
        /// <param name="strLogin">收件人登录Id</param>
        /// <param name="strType">邮件类型:9+ </param>
        /// <param name="strType">内容</param>
        private int SendEmailAsnyc(T_Message TMessage)
        {
            try
            {
                string pToEmail = "";
                int RandKey = 0;

                DataAccess da = new DataAccess();
                

                SmtpClient client = new SmtpClient("mail.antiwearvalve.com",25);
                
                #region 邮箱发件人 tmfrom

                    #region 测试环境
                client.Host = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailHost"]) ? "smtp.exmail.qq.com" : ConfigurationManager.AppSettings["EmailHost"];
                client.Port = 25;

                client.EnableSsl = false;

                string mFrom = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFrom"]) ? "moose.zhang@ztnet.com.cn" : ConfigurationManager.AppSettings["EmailFrom"];
                string mPassword = string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["EmailFromPwd"]) ? "Zsh768594" : ConfigurationManager.AppSettings["EmailFromPwd"];
                string mDisplayName = "Antiwear";
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(mFrom, mPassword);//用户名和密码         
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(mFrom, mDisplayName, System.Text.Encoding.UTF8);
                    #endregion

                    #region 正式环境

                //client.Host = "mail.antiwearvalve.com";
                //client.Port = 25;
                //client.EnableSsl = false;
                ////string mFrom = "antiwearvalve.com\\crm_service"; 
                ////string mPassword = "82880588"; 
                ////string mDisplayName = "Antiwear";
                //client.UseDefaultCredentials = false;

                //client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //MailMessage mail = new MailMessage();
                //mail.From = new System.Net.Mail.MailAddress("crm_service@antiwearvalve.com", "Antiwear", System.Text.Encoding.UTF8);
                    #endregion
                
                
                //mail.From = new MailAddress(mFrom, mDisplayName, System.Text.Encoding.UTF8);         
                //mail.To.Add("jinjie@antiwearvalve.com");
          
                #endregion

                #region 邮件收件人 tmto
                if (TMessage.tmType == "1")
                {
                    DataTable dt = GetMsgReceiver();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            mail.To.Add(new MailAddress(dr["value"].ToString()));
                        }
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    DataTable dt = GetLoginEmail(TMessage.tmto);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        return -1;
                    }
                    else
                    {
                        pToEmail = dt.Rows[0]["tauEmail"].ToString();
                    }

                    mail.To.Add(new MailAddress(pToEmail));
                }

                #endregion

                #region 邮件标题 tmTitle
                mail.Subject = string.IsNullOrWhiteSpace(TMessage.tmTitle) ? "安特威推送服务" : TMessage.tmTitle;
                #endregion

                #region 邮件内容 tmMessage
                //switch (TMessage.tmType)
                //{
                //    //推送默认管理员
                //    case "1":
                //        break;
                //    //推送客户
                //    case "2":
                //        break;
                //    //推送分供商
                //    case "3":
                //        break;
                //    //销售推送消息
                //    case "4":
                //        break;

                //}

                if (string.IsNullOrWhiteSpace(TMessage.tmMessage))
                {
                    DataTable dtMessage = da.ExecuteDataTable(string.Format("select dfValue from D_Foundation where dfType ='{0}'", TMessage.tmMessage));
                    if (dtMessage == null || dtMessage.Rows.Count <= 0)
                        return -1;

                    mail.Body = dtMessage.Rows[0]["dfValue"].ToString();
                }
                else
                {
                    mail.Body = TMessage.tmMessage;
                }
                #endregion


                


                client.Send(mail);

                return 1;
            }
            catch (Exception ex)
            {
                
                return -1;

                //Log
                //Util.WriteLog(Server, "SendMail EX:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取默认邮件管理人员地址
        /// </summary>
        /// <returns></returns>
        private DataTable GetMsgReceiver()
        {

            DataAccess da = new DataAccess();
            string strSql = "select value from D_SystemArgs where [key]='DefaultMsgReceiver' and rowstatus!=2";
            DataTable dt = da.ExecuteDataTable(strSql);

            return dt;
        }

        /// <summary>
        /// 获取目标邮箱地址
        /// </summary>
        /// <param name="strLoginId"></param>
        /// <returns></returns>
        private DataTable GetLoginEmail(string strLoginId)
        {
            DataAccess da = new DataAccess();
            string strSql = "select tauEmail from T_AppUser where tauLoginId='{0}'";

            strSql = string.Format(strSql, strLoginId);

            return da.ExecuteDataTable(strSql);
        }

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            else
            {
                return true;
            }
        }
        #endregion



        


    }
}
